import Express from "express";
import { MovieService } from "../services/MovieService";
import { ResponseHelper } from "./ResponseHelper";

const router = Express.Router();

// localhost:3000/api/movie/xxxxxxx param

// localhost:3000/api/movie?id=xxxx query

router.get("/:id", async (req, res) => {

    try {
        // res.send("get 请求");
        const movieid = req.params.id;
        const movie = await MovieService.findById(movieid);
        // 响应：服务器的接口的响应格式，往往是一个标准格式
        ResponseHelper.sendData(movie, res);
    } catch {
        ResponseHelper.sendData(null, res);
    }

    // res.send("get " + movieid);
});

router.get("/", async (req, res) => {
    const result = await MovieService.find(req.query);
    ResponseHelper.sendPageData(result, res);
});

router.post("/", async (req, res) => {
    // res.send("post 请求");
    const result = await MovieService.addMovie(req.body);
    console.log(result);
    if (Array.isArray(result)) {
        ResponseHelper.sendError(result, res);
    } else {
        ResponseHelper.sendData(result, res);
    }
});

router.put("/:id", async (req, res) => {

    try {
        const result = await MovieService.edit(req.params.id, req.body);
        if (result.length > 0) {
            ResponseHelper.sendError(result, res);
        } else {
            ResponseHelper.sendData(true, res);
        }
    } catch  {
        ResponseHelper.sendError("id错误", res);
    }
    // res.send("put 请求");
});

router.delete("/:id", async (req, res) => {
    try {
        const result = await MovieService.delete(req.params.id);
        ResponseHelper.sendData(true, res);
    } catch  {
        ResponseHelper.sendError("id错误", res);
    }
    // res.send("delete 请求");
});

export default router;
